const Car = require('../models/Car');
const pool = require('../config/database');
const Joi = require('joi');

// 验证规则
const createCarSchema = Joi.object({
  title: Joi.string().min(5).max(100).required(),
  subtitle: Joi.string().max(200).optional().allow(''),
  brand: Joi.string().required(),
  model: Joi.string().required(),
  reg_date: Joi.date().required(),
  distance: Joi.number().min(0).max(100).required(),
  gearbox: Joi.string().valid('manual', 'auto').required(),
  emission: Joi.string().required(),
  displacement: Joi.number().min(0.8).max(6.0).required(),
  color: Joi.string().optional().allow(''),
  price: Joi.number().min(1).max(1000).required(),
  original_price: Joi.number().min(1).max(1000).optional().allow(null),
  description: Joi.string().max(500).optional().allow(''),
  location: Joi.string().required(),
  contact_name: Joi.string().required(),
  contact_phone: Joi.string().pattern(/^1[3-9]\d{9}$/).required()
});

// 创建车辆
const createCar = async (req, res) => {
  try {
    // 验证请求数据
    const { error, value } = createCarSchema.validate(req.body);
    if (error) {
      return res.status(400).json({ message: error.details[0].message });
    }

    const sellerId = req.user.userId;

    // 创建车辆
    const carId = await Car.create({
      ...value,
      seller_id: sellerId
    });

    // 如果有上传的图片，保存图片信息
    if (req.files && req.files.length > 0) {
      const imageValues = req.files.map((file, index) => [
        carId,
        `/uploads/${file.filename}`,
        index === 0 // 第一张图片设为主图
      ]);

      await pool.query(
        'INSERT INTO car_images (car_id, image_url, is_main) VALUES ?',
        [imageValues]
      );
    }

    // 创建检测报告（模拟数据）
    const inspectionItems = [
      { item_name: '外观检测', passed: true, result_description: '轻微划痕' },
      { item_name: '内饰检测', passed: true, result_description: '正常磨损' },
      { item_name: '发动机检测', passed: true, result_description: '运转正常' },
      { item_name: '变速箱检测', passed: true, result_description: '换挡平顺' },
      { item_name: '底盘检测', passed: false, result_description: '轻微托底' },
      { item_name: '电子系统', passed: true, result_description: '功能正常' }
    ];

    const inspectionValues = inspectionItems.map(item => [
      carId,
      item.item_name,
      item.passed,
      item.result_description
    ]);

    await pool.query(
      'INSERT INTO inspections (car_id, item_name, passed, result_description) VALUES ?',
      [inspectionValues]
    );

    res.status(201).json({
      message: '车辆发布成功，等待审核',
      carId
    });
  } catch (error) {
    console.error('发布车辆错误:', error);
    res.status(500).json({ message: '服务器错误，发布失败' });
  }
};

// 获取车辆列表
const getCars = async (req, res) => {
  try {
    const {
      page = 1,
      limit = 1000,
      brand,
      keyword,
      priceRange,
      sort = 'default'
    } = req.query;

    const filters = {};
    if (brand) filters.brand = brand;
    if (keyword) filters.keyword = keyword;
    if (priceRange) filters.priceRange = priceRange;
    if (sort !== 'default') filters.sort = sort;

    const result = await Car.findAll(filters, parseInt(page), parseInt(limit));

    res.json(result);
  } catch (error) {
    console.error('获取车辆列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取车辆详情
const getCarDetail = async (req, res) => {
  try {
    const { id } = req.params;

    const car = await Car.findById(id);
    if (!car) {
      return res.status(404).json({ message: '车辆不存在' });
    }

    res.json(car);
  } catch (error) {
    console.error('获取车辆详情错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取用户发布的车辆
const getUserCars = async (req, res) => {
  try {
    const sellerId = req.user.userId;

    const cars = await Car.findBySeller(sellerId);

    res.json({ cars });
  } catch (error) {
    console.error('获取用户车辆错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 更新车辆信息
const updateCar = async (req, res) => {
  try {
    const { id } = req.params;
    const sellerId = req.user.userId;

    // 验证请求数据
    const { error, value } = createCarSchema.validate(req.body);
    if (error) {
      return res.status(400).json({ message: error.details[0].message });
    }

    // 检查车辆是否存在且属于当前用户
    const car = await Car.findById(id);
    if (!car) {
      return res.status(404).json({ message: '车辆不存在' });
    }

    if (car.seller_id !== sellerId) {
      return res.status(403).json({ message: '无权修改此车辆' });
    }

    // 更新车辆信息
    const success = await Car.update(id, value);
    if (!success) {
      return res.status(500).json({ message: '更新失败' });
    }

    res.json({ message: '更新成功' });
  } catch (error) {
    console.error('更新车辆错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 删除车辆
const deleteCar = async (req, res) => {
  try {
    const { id } = req.params;
    const sellerId = req.user.userId;

    // 检查车辆是否存在且属于当前用户
    const car = await Car.findById(id);
    if (!car) {
      return res.status(404).json({ message: '车辆不存在' });
    }

    if (car.seller_id !== sellerId) {
      return res.status(403).json({ message: '无权删除此车辆' });
    }

    // 删除车辆
    const success = await Car.delete(id);
    if (!success) {
      return res.status(500).json({ message: '删除失败' });
    }

    res.json({ message: '删除成功' });
  } catch (error) {
    console.error('删除车辆错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};
// 高级搜索功能
const advancedSearch = async (req, res) => {
  try {
    const {
      keyword,
      brand,
      minPrice,
      maxPrice,
      minDistance,
      maxDistance,
      gearbox,
      emission,
      location,
      year,
      page = 1,
      limit = 10,
      sort = 'newest'
    } = req.query;

    let query = `
      SELECT c.*, u.name as seller_name, u.avatar as seller_avatar,
             (SELECT image_url FROM car_images WHERE car_id = c.id AND is_main = TRUE LIMIT 1) as main_image
      FROM cars c
      LEFT JOIN users u ON c.seller_id = u.id
      WHERE c.status = 'approved'
    `;
    const params = [];

    // 构建高级筛选条件
    if (keyword) {
      query += ' AND (c.title LIKE ? OR c.description LIKE ? OR c.model LIKE ?)';
      const keywordParam = `%${keyword}%`;
      params.push(keywordParam, keywordParam, keywordParam);
    }

    if (brand) {
      query += ' AND c.brand = ?';
      params.push(brand);
    }

    if (minPrice || maxPrice) {
      if (minPrice && maxPrice) {
        query += ' AND c.price BETWEEN ? AND ?';
        params.push(parseFloat(minPrice), parseFloat(maxPrice));
      } else if (minPrice) {
        query += ' AND c.price >= ?';
        params.push(parseFloat(minPrice));
      } else if (maxPrice) {
        query += ' AND c.price <= ?';
        params.push(parseFloat(maxPrice));
      }
    }

    if (minDistance || maxDistance) {
      if (minDistance && maxDistance) {
        query += ' AND c.distance BETWEEN ? AND ?';
        params.push(parseFloat(minDistance), parseFloat(maxDistance));
      } else if (minDistance) {
        query += ' AND c.distance >= ?';
        params.push(parseFloat(minDistance));
      } else if (maxDistance) {
        query += ' AND c.distance <= ?';
        params.push(parseFloat(maxDistance));
      }
    }

    if (gearbox) {
      query += ' AND c.gearbox = ?';
      params.push(gearbox);
    }

    if (emission) {
      query += ' AND c.emission = ?';
      params.push(emission);
    }

    if (location) {
      query += ' AND c.location LIKE ?';
      params.push(`%${location}%`);
    }

    if (year) {
      query += ' AND YEAR(c.reg_date) = ?';
      params.push(parseInt(year));
    }

    // 排序
    let orderBy = 'c.created_at DESC';
    switch (sort) {
      case 'price_asc':
        orderBy = 'c.price ASC';
        break;
      case 'price_desc':
        orderBy = 'c.price DESC';
        break;
      case 'distance_asc':
        orderBy = 'c.distance ASC';
        break;
      case 'distance_desc':
        orderBy = 'c.distance DESC';
        break;
      case 'newest':
        orderBy = 'c.created_at DESC';
        break;
      case 'oldest':
        orderBy = 'c.created_at ASC';
        break;
    }
    query += ` ORDER BY ${orderBy}`;

    // 分页
    const offset = (page - 1) * limit;
    query += ' LIMIT ? OFFSET ?';
    params.push(parseInt(limit), offset);

    const [rows] = await pool.execute(query, params);

    // 获取总数
    let countQuery = 'SELECT COUNT(*) as total FROM cars c WHERE c.status = "approved"';
    const countParams = [];

    // 同样的筛选条件...
    if (keyword) {
      countQuery += ' AND (c.title LIKE ? OR c.description LIKE ? OR c.model LIKE ?)';
      const keywordParam = `%${keyword}%`;
      countParams.push(keywordParam, keywordParam, keywordParam);
    }

    // ... 其他筛选条件

    const [countRows] = await pool.execute(countQuery, countParams);
    const total = countRows[0].total;

    res.json({
      cars: rows,
      total,
      page: parseInt(page),
      limit: parseInt(limit),
      totalPages: Math.ceil(total / limit)
    });
  } catch (error) {
    console.error('高级搜索错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 获取品牌列表
const getBrands = async (req, res) => {
  try {
    const [rows] = await pool.execute(
      'SELECT DISTINCT brand FROM cars WHERE status = "approved" ORDER BY brand'
    );
    
    const brands = rows.map(row => ({
      value: row.brand,
      label: getBrandName(row.brand)
    }));

    res.json({ brands });
  } catch (error) {
    console.error('获取品牌列表错误:', error);
    res.status(500).json({ message: '服务器错误' });
  }
};

// 品牌名称映射
const getBrandName = (brand) => {
  const brandMap = {
    'volkswagen': '大众',
    'toyota': '丰田',
    'honda': '本田',
    'benz': '奔驰',
    'bmw': '宝马',
    'audi': '奥迪'
  };
  return brandMap[brand] || brand;
};
module.exports = {
  createCar,
  getCars,
  getCarDetail,
  getUserCars,
  updateCar,
  deleteCar
};
